from fastapi import FastAPI
from loguru import logger
from tortoise import Tortoise

from common.config import settings
from common.redis import RedisClient


def init_redis(app):
    app.state.redis_cli = RedisClient()
    logger.info('RedisClient初始化成功...')


async def close_redis(app):
    await app.state.redis_cli.close()
    logger.info('Redis DB all close...')


async def init_orm():
    await Tortoise.init(
        db_url=settings.MYSQL_DATABASE_URL,
        modules={'models': ['models']}
    )
    logger.info(f"Tortoise-ORM started ")


async def close_orm():
    await Tortoise.close_connections()
    logger.info("Tortoise-ORM shutdown")


def register_events(app: FastAPI):
    """注册事件"""
    @app.on_event("startup")
    async def startup():
        init_redis(app)
        await init_orm()

    @app.on_event("shutdown")
    async def shutdown():
        await close_redis(app)
        await close_orm()

